package com.waner.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.waner.reggie.common.BaseContext;
import com.waner.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录,拦截所有的请求路径
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 定义一个路径匹配器
    public static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1. 获取本次请求的URI
        String requestURI = request.getRequestURI();

        // 定义不需要处理的路径
        String[] frontUrls = new String[]{
                 "/front/**",          // 前台资源请求
                 "/common/**",    // 文件上传下载请求
                "/user/sendMsg",   // 用户登录发送请求
                "/user/login"

        };

        //
        String[] backendUrls = new String[]{
                "/employee/login",   // 员工登录请求
                "/employee/logout",  // 员工退出请求
                "/backend/**",       // 静态资源请求
                "/common/**"    // 文件上传下载请求
        };

        log.info("拦截到请求 {}",requestURI);

        // 2. 本次请求是否需要处理
        if(check(frontUrls,requestURI) || check(backendUrls,requestURI)){
            log.info("放行请求 {}",requestURI);
            // 如果当前的请求不需要进行拦截处理则放行
            filterChain.doFilter(request,response);
            return;
        }


        // 3. 判断用户是否完成登录
        Long id = (Long) request.getSession().getAttribute("employee");
        if(id != null){
            // 如果登录了则放行
            log.info("用户已登录， 用户的id为 {}",id);
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);

            return;
        }

        // 4. 判断移动端用户是否完成登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId != null){
            // 如果登录了则放行
            log.info("用户已登录， 用户的id为 {}",id);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);

            return;
        }

        log.info("用户未登录 {}",requestURI);

        // 4. 需要跳转，通过输出流的方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配，检查本次的请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        for(String uri:urls){
            if(PATH_MATCHER.match(uri,requestURI)){
                return true;
            }
        }
        return false;
    }
}
